package com.app.lxx.pregnancyberth;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.Application;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.util.Log;
import android.view.WindowManager;

import androidx.multidex.MultiDex;

import com.app.lxx.pregnancyberth.base.ANRService;
import com.app.lxx.pregnancyberth.base.ActivityManger;
import com.app.lxx.pregnancyberth.base.X5NetService;
import com.app.lxx.pregnancyberth.service.ButtonService;
import com.app.lxx.pregnancyberth.utils.NetReceiver;
import com.blankj.utilcode.util.Utils;
import com.lzy.okgo.OkGo;
import com.tencent.bugly.crashreport.CrashReport;
import com.zjy.portdemo.modbus.ModbusMaster;

import java.security.SecureRandom;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;


public class MyApplication extends Application {

    public static Context context;
    public static ModbusMaster modbusMaster;

    private NetReceiver mReceiver;

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    @Override
    public void onCreate() {
        super.onCreate();


        context = this;
        Utils.init(this);

        WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        int height = wm.getDefaultDisplay().getHeight();
        Log.d("MyApplication", "onCreate:height:"+height);


        try {
            /**
             * 初始化串口上下文、路径、波特率
             */
          if(!BuildConfig.DEBUG){
              //todo 串口初始化 测试临时注释
              modbusMaster = new ModbusMaster(this, "/dev/ttyS1", 9600);
              /**
               * 打开串口，并监听串口返回数据
               */
              modbusMaster.start();
          }
//            Lztek mLztek = Lztek.create(this);
//            mLztek.
            Log.e("ssss", "打开串口");
        } catch (Exception e) {
            e.printStackTrace();
        }


        okgoInit();
        preInitX5Core();

        Thread.setDefaultUncaughtExceptionHandler(restartHandler); // 程序崩溃时触发线程

        CrashReport.initCrashReport(getApplicationContext(), "951283d236", false);

        try {
            Intent intent = new Intent(this, ANRService.class);
            startService(intent);

        } catch (Exception e) {
            e.printStackTrace();
        }
        mReceiver = new NetReceiver();
        IntentFilter mFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mReceiver, mFilter);
        //按钮监听
        try {
            ButtonService.startWork();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void okgoInit() {
//        OkHttpClient.Builder builder = new OkHttpClient.Builder();
//        builder.connectTimeout(1000 * 60 * 3, TimeUnit.SECONDS);
//        builder.sslSocketFactory(createSSLSocketFactory());
//        builder.hostnameVerifier(new HostnameVerifier() {
//            @Override
//            public boolean verify(String hostname, SSLSession session) {
//                return true;
//            }
//        });
//
//        builder.cookieJar(new CookieJarImpl(new SPCookieStore(this)));
//        OkGo.getInstance().setOkHttpClient(builder.build()).init(this);
        OkGo.getInstance().init(this);
    }


    private SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory ssfFactory = null;

        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, new TrustManager[]{new TrustAllCerts()}, new SecureRandom());

            ssfFactory = sc.getSocketFactory();
        } catch (Exception e) {
        }

        return ssfFactory;
    }

    public class TrustAllCerts implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }

    private void preInitX5Core() {
        //预加载x5内核
        try {
            Intent intent = new Intent(this, X5NetService.class);
            startService(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    // 创建服务用于捕获崩溃异常
    private Thread.UncaughtExceptionHandler restartHandler = new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread thread, Throwable ex) {
            ex.printStackTrace();
            restartApp();//发生崩溃异常时,重启应用
        }
    };

    // 重启应用
    @SuppressLint("WrongConstant")
    public void restartApp() {
        Intent intent = new Intent();
        // 参数1：包名，参数2：程序入口的activity
        intent.setClassName(getPackageName(), "com.app.lxx.pregnancyberth.ui.MainActivity");
        PendingIntent restartIntent = PendingIntent.getActivity(
                getApplicationContext(), 0, intent,
                Intent.FLAG_ACTIVITY_NEW_TASK);
        AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, restartIntent); // 1秒钟后重启应用
        finishProgram(); // 自定义方法，关闭当前打开的所有avtivity
    }

    // activity管理：结束所有activity，彻底关闭应用
    public void finishProgram() {
        // for (Activity activity : activityList) {
        //     if (null != activity) {
        //         activity.finish();
        //     }
        // }
        ActivityManger.finshApp();
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(10);
    }

    @Override
    public void onTerminate() {
        unregisterReceiver(mReceiver);
        try {
            ButtonService.stopWork();
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onTerminate();
    }
}
